<!-- 景点选择器 -->
<template>
  <div class="fixed inset-0 z-50 overflow-hidden">
    <div class="absolute inset-0 overflow-hidden">
      <div class="absolute inset-0 bg-gray-500 bg-opacity-75 transition-opacity"></div>

      <div class="fixed inset-y-0 right-0 pl-10 max-w-full flex">
        <div class="w-screen max-w-4xl">
          <div class="h-full flex flex-col bg-white shadow-xl">
            <!-- 头部 -->
            <div class="px-6 py-4 border-b border-gray-200">
              <div class="flex items-start justify-between">
                <h2 class="text-lg font-medium text-gray-900">选择景点</h2>
                <button 
                  @click="$emit('close')"
                  class="text-gray-400 hover:text-gray-500"
                >
                  <font-awesome-icon icon="times" class="text-xl" />
                </button>
              </div>
            </div>

            <!-- 内容区域 -->
            <div class="flex-1 flex overflow-hidden">
              <!-- 左侧列表 -->
              <div class="w-1/2 flex flex-col border-r border-gray-200">
                <!-- 搜索和筛选 -->
                <div class="p-4 border-b border-gray-200">
                  <div class="space-y-4">
                    <SearchFilter 
                      v-model="searchQuery"
                      placeholder="搜索景点..."
                    />
                    <select 
                      v-model="selectedCategory"
                      class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="">全部分类</option>
                      <option v-for="category in categories" :key="category" :value="category">
                        {{ category }}
                      </option>
                    </select>
                  </div>
                </div>

                <!-- 景点列表 -->
                <div class="flex-1 overflow-y-auto">
                  <div class="divide-y divide-gray-200">
                    <div 
                      v-for="spot in filteredSpots"
                      :key="spot.id"
                      class="p-4 hover:bg-gray-50 cursor-pointer"
                      :class="{'bg-blue-50': selectedSpots.some(s => s.id === spot.id)}"
                      @click="toggleSpot(spot)"
                    >
                      <div class="flex items-center">
                        <img 
                          :src="spot.imageUrl"
                          :alt="spot.name"
                          class="w-16 h-16 rounded-lg object-cover"
                        />
                        <div class="ml-4">
                          <h4 class="text-sm font-medium text-gray-900">{{ spot.name }}</h4>
                          <p class="text-xs text-gray-500 mt-1">{{ spot.category }}</p>
                          <div class="flex items-center mt-1">
                            <span class="text-yellow-400 mr-1">
                              <font-awesome-icon icon="star" />
                            </span>
                            <span class="text-xs text-gray-600">{{ spot.rating }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 右侧地图 -->
              <div class="w-1/2 relative">
                <div id="spotSelectorMap" class="absolute inset-0"></div>
                <!-- 路线规划控制面板 -->
                <div class="absolute top-4 right-4 bg-white p-4 rounded-lg shadow-lg z-10">
                  <div class="space-y-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">规划方式</label>
                      <select 
                        v-model="routeType"
                        class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
                      >
                        <option value="driving">驾车</option>
                        <option value="walking">步行</option>
                        <option value="bicycling">骑行</option>
                        <option value="transit">公交</option>
                      </select>
                    </div>
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-1">优化方式</label>
                      <select 
                        v-model="routeOptimize"
                        class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
                      >
                        <option value="0">最短距离</option>
                        <option value="1">最短时间</option>
                        <option value="2">避开高速</option>
                      </select>
                    </div>
                    <button
                      @click="planRoute"
                      class="w-full px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
                      :disabled="selectedSpots.length < 2"
                    >
                      规划路线
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 底部已选景点 -->
            <div class="border-t border-gray-200">
              <div class="p-4">
                <div class="mb-2 flex justify-between items-center">
                  <h3 class="text-sm font-medium text-gray-700">已选景点</h3>
                  <span class="text-xs text-gray-500">{{ selectedSpots.length }} 个景点</span>
                </div>
                <div class="flex flex-wrap gap-2">
                  <div 
                    v-for="spot in selectedSpots"
                    :key="spot.id"
                    class="inline-flex items-center bg-blue-100 text-blue-800 rounded-full px-3 py-1"
                  >
                    <span class="text-sm">{{ spot.name }}</span>
                    <button 
                      @click="toggleSpot(spot)"
                      class="ml-2 text-blue-600 hover:text-blue-800"
                    >
                      <font-awesome-icon icon="times" class="text-xs" />
                    </button>
                  </div>
                </div>
              </div>

              <!-- 底部按钮 -->
              <div class="flex justify-end px-6 py-4 bg-gray-50">
                <button
                  @click="$emit('close')"
                  class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 mr-3"
                >
                  取消
                </button>
                <button
                  @click="handleConfirm"
                  class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
                >
                  确定
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import SearchFilter from './SearchFilter.vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps<{
  selectedSpotIds?: number[]
}>()

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'confirm', spots: any[]): void
}>()

// 状态管理
const searchQuery = ref('')
const selectedCategory = ref('')
const selectedSpots = ref<any[]>([])
const map = ref<any>(null)
const markers = ref<any[]>([])

// 路线规划相关
const routeType = ref('driving')
const routeOptimize = ref('0')
const driving = ref<any>(null)
const route = ref<any>(null)

// 常量
const categories = ['文化古迹', '自然风光', '博物馆', '特色美食', '休闲娱乐']

// 模拟数据
const spots = ref([
  {
    id: 1,
    name: '法门寺',
    category: '文化古迹',
    rating: 4.8,
    imageUrl: '/images/attractions/famensi.jpg',
    location: [107.385, 34.378]
  },
  {
    id: 2,
    name: '陈仓古城',
    category: '文化古迹',
    rating: 4.5,
    imageUrl: '/images/attractions/chencang.jpg',
    location: [107.369, 34.345]
  },
  {
    id: 3,
    name: '太白山',
    category: '自然风光',
    rating: 4.9,
    imageUrl: '/images/attractions/taibaishan.jpg',
    location: [107.415, 34.125]
  },
  {
    id: 4,
    name: '宝鸡青铜器博物馆',
    category: '博物馆',
    rating: 4.7,
    imageUrl: '/images/attractions/museum.jpg',
    location: [107.375, 34.365]
  }
])

// 计算属性
const filteredSpots = computed(() => {
  return spots.value.filter(spot => {
    const matchesSearch = spot.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesCategory = !selectedCategory.value || spot.category === selectedCategory.value
    return matchesSearch && matchesCategory
  })
})

// 初始化地图
const initMap = async () => {
  try {
    const AMap = await AMapLoader.load({
      key: 99c71af8ee148a433dd13f7893d13970', // 请替换为实际的高德地图 Key
      version: '2.0',
      plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.Driving']
    })

    map.value = new AMap.Map('spotSelectorMap', {
      zoom: 11,
      center: [107.385, 34.378], // 宝鸡市中心坐标
      mapStyle: 'amap://styles/whitesmoke'
    })

    // 添加控件
    map.value.addControl(new AMap.ToolBar())
    map.value.addControl(new AMap.Scale())
    map.value.addControl(new AMap.HawkEye({isOpen: true}))
    map.value.addControl(new AMap.MapType())

    // 初始化驾车路线规划
    driving.value = new AMap.Driving({
      map: map.value,
      panel: 'panel',
      policy: AMap.DrivingPolicy.LEAST_TIME,
      showTraffic: true
    })

    // 添加景点标记
    updateMarkers()
  } catch (error) {
    console.error('地图加载失败:', error)
  }
}

// 更新地图标记
const updateMarkers = () => {
  if (!map.value) return

  // 清除现有标记
  markers.value.forEach(marker => marker.remove())
  markers.value = []

  // 添加新标记
  spots.value.forEach(spot => {
    const isSelected = selectedSpots.value.some(s => s.id === spot.id)
    const marker = new AMap.Marker({
      position: spot.location,
      title: spot.name,
      icon: new AMap.Icon({
        size: new AMap.Size(32, 32),
        image: isSelected ? '/images/marker-selected.png' : '/images/marker.png',
        imageSize: new AMap.Size(32, 32)
      })
    })

    marker.on('click', () => {
      toggleSpot(spot)
    })

    marker.setMap(map.value)
    markers.value.push(marker)
  })
}

// 监听选中景点变化，更新地图标记和路线
watch(selectedSpots, () => {
  updateMarkers()
  if (selectedSpots.value.length >= 2) {
    planRoute()
  } else if (route.value) {
    map.value.remove(route.value)
    route.value = null
  }
})

// 监听路线类型变化
watch([routeType, routeOptimize], () => {
  if (selectedSpots.value.length >= 2) {
    planRoute()
  }
})

// 初始化选中景点
onMounted(() => {
  if (props.selectedSpotIds) {
    selectedSpots.value = spots.value.filter(spot => 
      props.selectedSpotIds?.includes(spot.id)
    )
  }
  initMap()
})

// 切换景点选中状态
const toggleSpot = (spot: any) => {
  const index = selectedSpots.value.findIndex(s => s.id === spot.id)
  if (index === -1) {
    selectedSpots.value.push(spot)
  } else {
    selectedSpots.value.splice(index, 1)
  }
}

// 规划路线
const planRoute = () => {
  if (!driving.value || selectedSpots.value.length < 2) return

  // 清除现有路线
  if (route.value) {
    map.value.remove(route.value)
  }

  // 设置路线规划策略
  let policy = AMap.DrivingPolicy.LEAST_TIME
  if (routeOptimize.value === '0') {
    policy = AMap.DrivingPolicy.LEAST_DISTANCE
  } else if (routeOptimize.value === '2') {
    policy = AMap.DrivingPolicy.LEAST_FEE
  }

  driving.value.setPolicy(policy)

  // 获取选中景点的坐标
  const waypoints = selectedSpots.value.map(spot => spot.location)

  // 规划路线
  driving.value.search(
    waypoints[0],
    waypoints[waypoints.length - 1],
    {
      waypoints: waypoints.slice(1, -1)
    },
    (status: string, result: any) => {
      if (status === 'complete') {
        console.log('路线规划完成')
        route.value = result.routes[0]
        
        // 计算总距离和时间
        const totalDistance = route.value.distance
        const totalTime = route.value.time
        
        // 显示路线信息
        const infoWindow = new AMap.InfoWindow({
          content: `<div class="p-2">
            <p>总距离：${(totalDistance / 1000).toFixed(1)}公里</p>
            <p>预计时间：${Math.floor(totalTime / 60)}分钟</p>
          </div>`,
          offset: new AMap.Pixel(0, -30)
        })
        
        infoWindow.open(map.value, route.value.path[0])
      } else {
        console.error('路线规划失败:', result)
      }
    }
  )
}

// 确认选择
const handleConfirm = () => {
  emit('confirm', selectedSpots.value)
  emit('close')
}
</script>

<style scoped>
.overflow-y-auto {
  scrollbar-width: thin;
  scrollbar-color: #888 #f1f1f1;
}

.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #666;
}

/* 确保地图容器有正确的高度 */
#spotSelectorMap {
  height: 100%;
  width: 100%;
}
</style> 